﻿using RestSharp;
using RestSharp.Interceptors;
using System.Collections.Concurrent;
using System.Text;
using XYS.Core.Models;
using XYS.Service.Core.Util.HttpInterceptors;

namespace XYS.Core.Util.Helper
{
    /// <summary>
    /// http 帮助类
    /// </summary>
    public static class HttpHelper
    {
        private static readonly ConcurrentDictionary<string, Lazy<RestClient>> clientMap = new();
        /// <summary>
        /// 拦截器
        /// </summary>
        public static List<Interceptor> Interceptors = new();


        /// <summary>
        /// 获取或创建 RestClient（自动缓存）
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        public static RestClient GetClient(string host) => GetClient(host, null);

        /// <summary>
        /// 获取或创建 RestClient（自动缓存）
        /// </summary>
        /// <param name="host"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static RestClient GetClient(string host, List<Interceptor> interceptors)
        {
            if (string.IsNullOrWhiteSpace(host)) return null;

            var lazyClient = clientMap.GetOrAdd(host, key =>
                new Lazy<RestClient>(() => CreateRestClient(key, interceptors)));
            return lazyClient.Value;
        }

        private static RestClient CreateRestClient(string host, List<Interceptor> interceptors)
        {
            interceptors ??= new();
            interceptors.Insert(0, new LogInterceptors());
            var options = new RestClientOptions(host)
            {
                // 忽略证书验证错误（过期、不受信任、域名不匹配等）
                RemoteCertificateValidationCallback = (sender, cert, chain, errors) => true,
                // 过滤器
                Interceptors = interceptors,
                // 编码
                Encoding = Encoding.UTF8,
                // 超时时间
                Timeout = TimeSpan.FromMinutes(30),
            };
            return new RestClient(options);
        }

        /// <summary>
        /// 默认的 Headers
        /// </summary>
        public static List<KeyValuePair<string, string>> DefaultHeaders { get; set; } = new List<KeyValuePair<string, string>>()
        {
            new("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0")
        };


        /// <summary>
        /// 发送请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T Execute<T>(HttpRequestModel request)
        {
            if (request == null) throw new ArgumentNullException(nameof(request));
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);

            var restRequest = BuildRequest(request);

            var res = client.Execute(restRequest);
            if (!res.IsSuccessful)
                throw new Exception($"请求出现错误:{res.StatusCode}:{res.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(res.Content as object);//直接返回 Content
            return res.Content.ToObject<T>();
        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static ResultModel<string> Execute(HttpRequestModel request)
        {
            try
            {
                var result = Execute<string>(request);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static async Task<T> ExecuteAsync<T>(HttpRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);

            var restRequest = BuildRequest(request);

            var res = await client.ExecuteAsync(restRequest).ConfigureAwait(false);
            if (!res.IsSuccessful)
                throw new Exception($"请求出现错误:{res.StatusCode}:{res.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(res.Content as object);//直接返回 Content
            return res.Content.ToObject<T>();

        }

        /// <summary>
        /// 发送请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static async Task<RestResponse> ExecuteRestAsync(HttpRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);
            var restRequest = BuildRequest(request);
            RestResponse res = await client.ExecuteAsync(restRequest).ConfigureAwait(false);
            return res;
        }

        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static async Task<ResultModel<string>> ExecuteAsync(HttpRequestModel request)
        {
            try
            {
                var result = await ExecuteAsync<string>(request).ConfigureAwait(false);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }
        /// <summary>
        /// 发送表单请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T Execute<T>(HttpFormDataRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);
            var restRequest = BuildFormDataRequest(request);
            RestResponse response = client.Execute(restRequest);
            if (!response.IsSuccessful) throw new Exception($"请求出现错误:{response.StatusCode}:{response.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(response.Content as object);//直接返回 Content
            return response.Content.ToObject<T>();
        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static ResultModel<string> Execute(HttpFormDataRequestModel request)
        {
            try
            {
                var result = Execute<string>(request);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }
        /// <summary>
        /// 发送表单请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static async Task<T> ExecuteAsync<T>(HttpFormDataRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);
            var restRequest = BuildFormDataRequest(request);
            RestResponse response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);
            if (!response.IsSuccessful) throw new Exception($"请求出现错误:{response.StatusCode}:{response.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(response.Content as object);//直接返回 Content
            return response.Content.ToObject<T>();
        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static async Task<ResultModel<string>> ExecuteAsync(HttpFormDataRequestModel request)
        {
            try
            {
                var result = await ExecuteAsync<string>(request).ConfigureAwait(false);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }















        /// <summary>
        /// 发送表单请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T Execute<T>(HttpFormUrlEncodedDataRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);
            var restRequest = BuildFormDataRequest(request);

            RestResponse response = client.Execute(restRequest);
            if (!response.IsSuccessful) throw new Exception($"请求出现错误:{response.StatusCode}:{response.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(response.Content as object);//直接返回 Content
            return response.Content.ToObject<T>();

        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static ResultModel<string> Execute(HttpFormUrlEncodedDataRequestModel request)
        {
            try
            {
                var result = Execute<string>(request);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }
        /// <summary>
        /// 发送表单请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static async Task<T> ExecuteAsync<T>(HttpFormUrlEncodedDataRequestModel request)
        {
            if (request.Method == null) throw new ArgumentNullException(nameof(request.Method));
            if (string.IsNullOrWhiteSpace(request.Host)) throw new ArgumentNullException(nameof(request.Host));

            var client = GetClient(request.Host);
            var restRequest = BuildFormDataRequest(request);

            RestResponse response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);
            if (!response.IsSuccessful) throw new Exception($"请求出现错误:{response.StatusCode}:{response.Content}");

            //字符串类型需要特殊处理
            if (typeof(T).ToString() == typeof(string).ToString())
                return (T)(response.Content as object);//直接返回 Content
            return response.Content.ToObject<T>();

        }
        /// <summary>
        /// 发送请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static async Task<ResultModel<string>> ExecuteAsync(HttpFormUrlEncodedDataRequestModel request)
        {
            try
            {
                var result = await ExecuteAsync<string>(request).ConfigureAwait(false);
                return ResultModel.Successed(result);
            }
            catch (Exception ex)
            {
                return ResultModel<string>.Failed(ex.Message);
            }
        }



        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="request"></param>
        /// <param name="fileName">本地文件路径</param>
        /// <param name="overwrite">如果文件已存在，是否覆盖</param>
        /// <returns></returns>
        public static async Task<ResultModel> DownLoadFileAsync(HttpRequestModel request, string fileName, bool overwrite = true)
        {
            fileName = fileName.Replace('\\', Path.DirectorySeparatorChar);
            if (!overwrite && File.Exists(fileName)) return ResultModel.Failed("文件已存在", 400);
            if (string.IsNullOrWhiteSpace(request.Host)) return ResultModel.Failed("参数 Host 不存在", 400);

            try
            {
                var client = GetClient(request.Host);

                var restRequest = BuildRequest(request);
                if (restRequest.Method == Method.Options) restRequest.Method = Method.Get;

                string filePath = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);

                using var stream = await client.DownloadStreamAsync(restRequest).ConfigureAwait(false);
                fileName.DeleteFile();
                using (var writer = File.OpenWrite(fileName))
                { stream.CopyTo(writer); }

                return ResultModel.Success;
            }
            catch (Exception ex)
            {
                return ResultModel.Failed(ex.ToJson(), 500);
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="request"></param>
        /// <param name="fileName">本地文件路径</param>
        /// <param name="overwrite">如果文件已存在，是否覆盖</param>
        /// <returns></returns>
        public static ResultModel DownLoadFile(HttpRequestModel request, string fileName, bool overwrite = true)
        {
            fileName = fileName.Replace('\\', Path.DirectorySeparatorChar);
            if (!overwrite && File.Exists(fileName)) return ResultModel.Failed("文件已存在", 400);
            if (string.IsNullOrWhiteSpace(request.Host)) return ResultModel.Failed("参数 Host 不存在", 400);

            try
            {
                var client = GetClient(request.Host);

                var restRequest = BuildRequest(request);
                if (restRequest.Method == Method.Options)
                    restRequest.Method = Method.Get;

                string filePath = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);

                var fileData = client.DownloadData(restRequest);
                fileName.DeleteFile();
                File.WriteAllBytes(fileName, fileData);

                return ResultModel.Success;
            }
            catch (Exception ex)
            {
                return ResultModel.Failed(ex.ToJson(), 500);
            }
        }


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteUrl"></param>
        /// <param name="fileName">本地文件路径</param>
        /// <param name="overwrite">如果文件已存在，是否覆盖</param>
        /// <returns></returns>
        public static Task<ResultModel> DownLoadFileAsync(string remoteUrl, string fileName, bool overwrite = true)
        {
            if (string.IsNullOrWhiteSpace(remoteUrl)) return Task.FromResult(ResultModel.Failed("文件不存在"));
            var remoteUri = new Uri(remoteUrl);

            return DownLoadFileAsync(new HttpRequestModel()
            {
                Method = HttpMethod.Get,
                Host = $"{remoteUri.Scheme}://{remoteUri.Authority}",
                Path = remoteUri.PathAndQuery,
                Timeout = TimeSpan.FromMinutes(5)
            }, fileName, overwrite);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteUrl"></param>
        /// <param name="fileName">本地文件路径</param>
        /// <param name="overwrite">如果文件已存在，是否覆盖</param>
        /// <returns></returns>
        public static ResultModel DownLoadFile(string remoteUrl, string fileName, bool overwrite = true)
        {
            if (string.IsNullOrWhiteSpace(remoteUrl)) return ResultModel.Failed("文件不存在");
            var remoteUri = new Uri(remoteUrl);

            return DownLoadFile(new HttpRequestModel()
            {
                Method = HttpMethod.Get,
                Host = $"{remoteUri.Scheme}://{remoteUri.Authority}",
                Path = remoteUri.PathAndQuery,
                Timeout = TimeSpan.FromMinutes(5)
            }, fileName, overwrite);
        }




        /// <summary>
        /// 发送 Get 请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static T Get<T>(HttpRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return Execute<T>(request);
        }

        /// <summary>
        /// 发送 Get 请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        public static async Task<T> GetAsync<T>(HttpRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }

        /// <summary>
        /// 发送 Get 请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static ResultModel<string> Get(HttpRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return Execute(request);
        }
        /// <summary>
        /// 发送 Get 请求
        /// 请求失败时 不会抛异常
        /// </summary>
        public static async Task<ResultModel<string>> GetAsync(HttpRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }



        /// <summary>
        /// 发送 POST 请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Post<T>(HttpRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return Execute<T>(request);
        }
        /// <summary>
        /// 发送 POST 请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<T> PostAsync<T>(HttpRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }
        /// <summary>
        /// 发送 POST 请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultModel<string> Post(HttpRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return Execute(request);
        }
        /// <summary>
        /// 发送 POST 请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<ResultModel<string>> PostAsync(HttpRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }







        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Get<T>(HttpFormDataRequestModel request)
            where T : class
        {
            request.Method = HttpMethod.Get;
            return Execute<T>(request);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultModel<string> Get(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return Execute(request);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<ResultModel<string>> GetAsync(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }







        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Post<T>(HttpFormDataRequestModel request)
            where T : class
        {
            request.Method = HttpMethod.Post;
            return Execute<T>(request);
        }
        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<T> PostAsync<T>(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }

        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultModel<string> Post(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return Execute(request);
        }

        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<ResultModel<string>> PostAsync(HttpFormDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }














        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Get<T>(HttpFormUrlEncodedDataRequestModel request)
            where T : class
        {
            request.Method = HttpMethod.Get;
            return Execute<T>(request);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultModel<string> Get(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Get;
            return Execute(request);
        }
        /// <summary>
        /// 发送 Get 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<ResultModel<string>> GetAsync(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }







        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Post<T>(HttpFormUrlEncodedDataRequestModel request)
            where T : class
        {
            request.Method = HttpMethod.Post;
            return Execute<T>(request);
        }
        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 会抛异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<T> PostAsync<T>(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync<T>(request).ConfigureAwait(false);
        }

        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultModel<string> Post(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return Execute(request);
        }

        /// <summary>
        /// 发送 POST 表单请求
        /// 请求失败时 不会抛异常
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<ResultModel<string>> PostAsync(HttpFormUrlEncodedDataRequestModel request)
        {
            request.Method = HttpMethod.Post;
            return await ExecuteAsync(request).ConfigureAwait(false);
        }











        /// <summary>
        /// 请求参数
        /// </summary>
        public class HttpRequestModel
        {
            /// <summary>
            /// 请求枚举
            /// </summary>
            public HttpMethod Method { get; set; }
            /// <summary>
            /// host
            /// </summary>
            public string Host { get; set; }
            /// <summary>
            /// path
            /// </summary>
            public string Path { get; set; }
            /// <summary>
            /// headers
            /// </summary>
            public ICollection<KeyValuePair<string, string>> Headers { get; set; }
            /// <summary>
            /// body
            /// </summary>
            public object Body { get; set; }

            /// <summary>
            /// 超时时间
            /// 默认30s
            /// </summary>
            public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(3);
        }

        /// <summary>
        /// 表单提交 请求参数
        /// </summary>
        public class HttpFormDataRequestModel
        {
            /// <summary>
            /// 请求枚举
            /// </summary>
            public HttpMethod Method { get; set; }
            /// <summary>
            /// rest method
            /// </summary>
            public Method RestMethod
            {
                get
                {
                    if (Method == HttpMethod.Get) return RestSharp.Method.Get;
                    if (Method == HttpMethod.Post) return RestSharp.Method.Post;
                    if (Method == HttpMethod.Delete) return RestSharp.Method.Delete;
                    if (Method == HttpMethod.Put) return RestSharp.Method.Put;
                    if (Method == HttpMethod.Patch) return RestSharp.Method.Patch;
                    if (Method == HttpMethod.Options) return RestSharp.Method.Options;
                    if (Method == HttpMethod.Head) return RestSharp.Method.Head;
                    return RestSharp.Method.Get;
                }
            }

            /// <summary>
            /// host
            /// </summary>
            public string Host { get; set; }
            /// <summary>
            /// path
            /// </summary>
            public string Path { get; set; }
            /// <summary>
            /// queryParameters
            /// </summary>
            public ICollection<KeyValuePair<string, string>> QueryParameters { get; set; }
            /// <summary>
            /// headers
            /// </summary>
            public ICollection<KeyValuePair<string, string>> Headers { get; set; }

            /// <summary>
            /// 超时时间
            /// 默认30s
            /// </summary>
            public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(3);

            /// <summary>
            /// 文件列表
            /// </summary>
            public ICollection<KeyValuePair<string, HttpRequestFileModel>> Files { get; set; }
        }


        /// <summary>
        /// x-www-form-urlencoded 请求参数
        /// </summary>
        public class HttpFormUrlEncodedDataRequestModel
        {
            /// <summary>
            /// 请求枚举
            /// </summary>
            public HttpMethod Method { get; set; }
            /// <summary>
            /// rest method
            /// </summary>
            public Method RestMethod
            {
                get
                {
                    if (Method == HttpMethod.Get) return RestSharp.Method.Get;
                    if (Method == HttpMethod.Post) return RestSharp.Method.Post;
                    if (Method == HttpMethod.Delete) return RestSharp.Method.Delete;
                    if (Method == HttpMethod.Put) return RestSharp.Method.Put;
                    if (Method == HttpMethod.Patch) return RestSharp.Method.Patch;
                    if (Method == HttpMethod.Options) return RestSharp.Method.Options;
                    if (Method == HttpMethod.Head) return RestSharp.Method.Head;
                    return RestSharp.Method.Get;
                }
            }
            /// <summary>
            /// host
            /// </summary>
            public string Host { get; set; }
            /// <summary>
            /// path
            /// </summary>
            public string Path { get; set; }
            /// <summary>
            /// queryParameters
            /// </summary>
            public ICollection<KeyValuePair<string, string>> QueryParameters { get; set; }
            /// <summary>
            /// headers
            /// </summary>
            public ICollection<KeyValuePair<string, string>> Headers { get; set; }

            /// <summary>
            /// 超时时间
            /// 默认30s
            /// </summary>
            public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(3);
        }


        /// <summary>
        /// 文件参数
        /// </summary>
        public class HttpRequestFileModel
        {
            /// <summary>
            /// 文件名
            /// </summary>
            public string FileName { get; set; }
            /// <summary>
            /// 文件
            /// </summary>
            public byte[] FileData { get; set; }
            /// <summary>
            /// 文件流
            /// </summary>
            public Stream FileStream { get; set; }
        }

        /// <summary>
        /// 构建请求参数
        /// </summary>
        /// <returns></returns>
        private static RestRequest BuildRequest(HttpRequestModel request)
        {
            var restRequest = new RestRequest(request.Path, Method.Options);
            if (request.Method != null)
            {
                if (request.Method.Method == HttpMethod.Get.Method)
                    restRequest.Method = Method.Get;
                else if (request.Method.Method == HttpMethod.Post.Method)
                    restRequest.Method = Method.Post;
                else if (request.Method.Method == HttpMethod.Put.Method)
                    restRequest.Method = Method.Put;
                else if (request.Method.Method == HttpMethod.Delete.Method)
                    restRequest.Method = Method.Delete;
            }

            //添加默认的Headers
            restRequest.AddOrUpdateHeaders(DefaultHeaders);

            //添加头部参数
            if (request.Headers != null)
                restRequest.AddOrUpdateHeaders(request.Headers);
            //添加body参数
            if (request.Body != null)
            {
                if (request.Body.GetType() != typeof(string))
                {
                    string bodyJson = request.Body.ToJson();
                    restRequest.AddStringBody(bodyJson, DataFormat.Json);
                }
                else restRequest.AddStringBody(request.Body.ToString(), DataFormat.Json);
            }

            //超时时间
            restRequest.Timeout = XYS.Service.Core.Util.DateTimeHelper.Max(request.Timeout, TimeSpan.Zero);

            return restRequest;
        }

        /// <summary>
        /// 构建表单请求参数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static RestRequest BuildFormDataRequest(HttpFormDataRequestModel request)
        {
            var restRequest = new RestRequest($"{request.Host}{request.Path}", request.RestMethod);

            var headers = DefaultHeaders.Clone();
            //添加头部参数
            if (request.Headers != null)
            {
                foreach (var headersItem in request.Headers)
                    headers.Add(headersItem);
            }
            headers = headers.DistinctBy(x => x.Key).ToList();
            restRequest.AddHeaders(headers);

            if (!request.Files.IsNullOrEmpty())
            {
                foreach (var file in request.Files)
                {
                    if (file.Value != null && (file.Value.FileData?.Any() == true || file.Value.FileStream != null))
                    {
                        if (file.Value.FileStream != null)
                            restRequest.AddFile(file.Key, () => file.Value.FileStream, file.Value.FileName.ToLower());
                        else
                            restRequest.AddFile(file.Key, file.Value.FileData, file.Value.FileName.ToLower());
                    }
                }
            }

            //添加请求参数
            if (!request.QueryParameters.IsNullOrEmpty())
            {
                foreach (var queryParameter in request.QueryParameters)
                    restRequest.AddParameter(queryParameter.Key, queryParameter.Value, ParameterType.GetOrPost);
            }
            return restRequest;
        }


        /// <summary>
        /// 构建表单请求参数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static RestRequest BuildFormDataRequest(HttpFormUrlEncodedDataRequestModel request)
        {
            var restRequest = new RestRequest($"{request.Host}{request.Path}", request.RestMethod);
            var headers = DefaultHeaders.Clone();
            //添加头部参数
            if (request.Headers != null)
            {
                foreach (var headersItem in request.Headers)
                    headers.Add(headersItem);
            }
            headers = headers.DistinctBy(x => x.Key).ToList();
            restRequest.AddHeaders(headers);


            //添加请求参数
            if (!request.QueryParameters.IsNullOrEmpty())
            {
                foreach (var queryParameter in request.QueryParameters)
                    restRequest.AddParameter(queryParameter.Key, queryParameter.Value);
            }



            return restRequest;
        }

    }
}
